package org.jaaksi.test.handler;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MyActivity extends Activity {
    private static final int FADE_OUT = 0;
    private static final int SHOW_PROGRESS = 1;

    private int num = 0;

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FADE_OUT:
                    Log.i("fcy", "--------- has3=" + hasMessages(3));
                    Message message = obtainMessage(3); // 消息池没有，则会创建一个消息
                    Log.i("fcy", "---------obtainMessage(3) has3=" + hasMessages(3));
                    sendMessage(message);
                    Log.i("fcy", "---------sendMessage obtainMessage(3) has3=" + hasMessages(3));
                    removeMessages(3);
                    Log.i("fcy", "---------removeMessages(3) has3=" + hasMessages(3));
                    removeMessages(SHOW_PROGRESS);
                    btn.setText("暂停");
                    break;
                case SHOW_PROGRESS:
                    btn.setEnabled(false);
                    if (num <= 100) {
                        btn.setText(String.valueOf(num++));
                        sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
                    } else {
                        btn.setText("停止");
                    }
                    break;
            }
        }
    };

    private Button btn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        btn = (Button) findViewById(R.id.count);
    }

    public void start(View view) {
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
        mHandler.sendEmptyMessageDelayed(SHOW_PROGRESS, 1000);
    }

    public void pause(View view) {
        mHandler.sendEmptyMessageDelayed(FADE_OUT, 0);
    }
}
